import java.util.Iterator;
import java.util.function.Consumer;

public class DynamicArray implements Iterator<Integer>{
    private static int size = 0;
    private static int capacity = 8;
    private static int[] array;

    public static void addLast(int element) {
        add(size,element);
    }

    private static void checkAndGrow() {
        if (size == 0) {
            array = new int[capacity];
        }
        if (size == capacity) {
            //扩容
            capacity += capacity >> 1;
            int[] newArray = new int[capacity];
            System.arraycopy(array, 0, newArray, 0, size);
            array = newArray;
        }
    }
    public static void add(int index , int element) {
        checkAndGrow();
        if (index >= 0 && index < size) {
            System.arraycopy(array , index, array , index + 1, size-index);

        }
        array[index] = element;
        size++;
    }
    //返回指定下标的元素
    public static int get(int index) {
        return array[index];
    }

    //遍历数组
    public  static void forEach() {
        for (int i = 0; i < size; i++) {
            System.out.println(array[i]);
        }
    }

    public  static void foreach(Consumer<Integer> consumer) {
        for (int i = 0; i < size; i++) {
            consumer.accept(array[i]);
        }
    }
    //用迭代器实现遍历
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int i = 0;
            @Override
            public boolean hasNext() {//判断是否有下一个
                return i < size;
            }

            @Override
            public Integer next() {//返回当前元素，并移动到下一个元素
                return array[i++];
            }
        };
    }

    //删除指定下标的元素
    public static int remove(int index) {
        int removed = array[index];
        if (index < size - 1) {
            System.arraycopy(array,index+1,array,index,size-index-1);
        }
        size--;
        return removed;
    }

    @Override
    public boolean hasNext() {
        return false;
    }

    @Override
    public Integer next() {
        return null;
    }
}
